Retain cycle on `self` with blocks

Posted by Jonathan Sterling on Stack Overflow See other posts from Stack Overflow or by Jonathan Sterling
Published on 2010-12-04T07:55:40Z Indexed on 2011/01/02 7:53 UTC
Read the original article Hit count: 227

I'm afraid this question is pretty basic, but I think it's relevant to a lot of Objective-C programmers who are getting into blocks.

What I've heard is that since blocks capture local variables referenced within them as const copies, using self within a block can result in a retain cycle, should that block be copied. So, we are supposed to use __block to force the block to deal directly with self instead of having it copied.

__block typeof(self) bself = self;
[someObject messageWithBlock:^{ [bself doSomething]; }];

instead of just

[someObject messageWithBlock:^{ [self doSomething]; }];

What I'd like to know is the following: if this is true, is there a way that I can avoid the ugliness (aside from using GC)?

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about memory-management